package com.example.wangning.mycarofcountry.recommend.evaluating;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.mycarofcountry.entity.dao.Recommend_Evaluating;
import com.example.wangning.mycarofcountry.R;
import com.example.wangning.mycarofcountry.cache.VolleySingleton;
import com.example.wangning.mycarofcountry.db.DaoHelper;
import com.example.wangning.mycarofcountry.tool.DividerGridItemDecoration;
import com.example.wangning.mycarofcountry.tool.MyDialog;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 16/1/6.
 */
public class EvaluatingFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    private RecyclerView recyclerView;
    private EvaluatingAdapter evaluatingAdapter;
    private VolleySingleton queue;
    private SwipeRefreshLayout news_Swipe;
    private TextView news_Tv;
    private int lastVisibleItem;
    private boolean isRefresh = true;
    private LinearLayoutManager manager;
    private DaoHelper helper;
    private MyDialog myDialog;
    private String url = "http://app.api.autohome.com.cn/autov4.8.5/news/shuokelist-pm2-s20-lastid0.json";
    private String nextUrl = "http://app.api.autohome.com.cn/autov5.0.0/news/shuokelist-pm2-s20-lastid20151107140000501625.json";

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_evaluating, null);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        news_Swipe = (SwipeRefreshLayout) view.findViewById(R.id.news_Swipe);
        news_Tv = (TextView) view.findViewById(R.id.news_Tv);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        manager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(manager);
        recyclerView.addItemDecoration(new DividerGridItemDecoration(getActivity()));
        evaluatingAdapter = new EvaluatingAdapter(getActivity());
        recyclerView.setAdapter(evaluatingAdapter);
        helper = DaoHelper.getInstance();
        List<Recommend_Evaluating> evaluatingList = helper.searchEvaluating();
        myDialog = new MyDialog(getActivity(),"正在加载...",R.drawable.anim_set);
        myDialog.setCanceledOnTouchOutside(true);//设置点击以外区域不消失属性
        if (evaluatingList == null || evaluatingList.size() == 0) {
            myDialog.show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    myDialog.dismiss();
                }
            },3000);
            initData(url);
        } else {
            evaluatingAdapter.addRefreshData(evaluatingList);

        }
        setrefresh();

    }

    private void setrefresh() {
        //设置刷新时动画的颜色，可以设置4个
        news_Swipe.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        news_Swipe.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        news_Swipe.setOnRefreshListener(this);


        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView,
                                             int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == evaluatingAdapter.getItemCount()) {
                    onLoad();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = manager.findLastVisibleItemPosition();
            }
        });
        recyclerView.setHasFixedSize(true);
    }

    private void onLoad() {
        isRefresh = false;
        newsHandler.sendEmptyMessageDelayed(0, 3000);
    }

    private void initData(String url) {
        queue = VolleySingleton.getVolleyIntance();
        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                EvaluatingBean evaluatingBean = gson.fromJson(response, EvaluatingBean.class);
                if (evaluatingBean != null) {
                    EvaluatingResult evaluatingResult = evaluatingBean.getResult();
                    List<Recommend_Evaluating> evaluatings = evaluatingResult.getList();
                    if (isRefresh) {
                        evaluatingAdapter.addRefreshData(evaluatings);
                    } else {
                        evaluatingAdapter.addLoadData(evaluatings);
                    }
                    if (evaluatings != null && evaluatings.size() > 0){
                        helper.addEvaluating(evaluatings);
                    }
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {

                            news_Tv.setVisibility(View.GONE);
                        }
                    }, 1000);
                    news_Swipe.setRefreshing(false);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                evaluatingAdapter.addRefreshData(helper.searchEvaluating());
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                try {
                    String jsonString = new String(response.data, "UTF-8");
                    return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (Exception je) {
                    return Response.error(new ParseError(je));
                }
            }
        };
        queue.addRequest(stringRequest);
    }

    @Override
    public void onRefresh() {
        newsHandler.sendEmptyMessageDelayed(1, 3000);
    }

    private Handler newsHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0://上拉加载
                    onLoad();
                    initData(nextUrl);
                    news_Swipe.setRefreshing(false);
                    break;
                case 1:
                    news_Tv.setVisibility(View.VISIBLE);
                    news_Tv.setText("刷新完成");
                    news_Swipe.setRefreshing(false);
                    initData(url);
                    break;
            }
        }
    };
}
